<template>
	<view class="form-main">
		<u-form labelPosition="left" :model="form" :rules="rules" ref="uForm" :errorType="['message']">
			<view class="form-title u-text-center u-m-b-18">请您填写来访资料，带<text style="color: red;">*</text>号为必填</view>
			<view class="form-box">
				<u-form-item label="来访开始日期" label-width="200rpx" prop="lfTime" required>
					<view class="u-flex select-box" @click="dateShow = true">
						<u-input class="u-flex-1 form-input" placeholder="请选择申请来访开始日期" v-model="form.lfTime" readonly />
					</view>
					<u-datetime-picker ref="datetimePicker" :show="dateShow" mode="datetime" :formatter="formatter"
						:minDate="new Date().getTime()" :maxDate="new Date().getTime() + 2592000000"
						@cancel="dateShow = false" @close="dateShow = false" @confirm="onConfirmType" closeOnClickOverlay></u-datetime-picker>
				</u-form-item>
				<u-form-item label="来访结束日期" label-width="200rpx" prop="visitTimeEnd" required>
					<view class="u-flex select-box" @click="dateShow1 = true">
						<u-input class="u-flex-1 form-input" placeholder="请选择申请来访结束日期" v-model="form.visitTimeEnd" readonly />
					</view>
					<u-datetime-picker ref="datetimePicker" :show="dateShow1" mode="datetime" :formatter="formatter"
						:minDate="new Date().getTime()" :maxDate="new Date().getTime() + 2592000000"
						@cancel="dateShow1 = false" @close="dateShow1 = false" @confirm="onConfirmType1" closeOnClickOverlay></u-datetime-picker>
				</u-form-item>
				<u-form-item label="申请人" label-width="110rpx" prop="userName" required>
					<u-input class="form-input" v-model="form.userName" placeholder="请输入申请人" clearable />
				</u-form-item>
				<u-form-item label="申请人电话" label-width="170rpx" prop="userPhone" required>
					<u-input class="form-input" v-model="form.userPhone" placeholder="请输入申请人电话" clearable />
				</u-form-item>
				<u-form-item label="拜访部门" label-width="140rpx" prop="bfDeptName" required>
					<view class="u-flex select-box" @click="openDeptShow">
						<u-input class="u-flex-1 form-input"
							placeholder="请选择拜访部门" v-model="form.bfDeptName" readonly />
					</view>
					<!-- <u-picker title="选择要拜访的部门" :show="deptShow" :columns="deptList" keyName="deptName"
						@cancel="deptShow = false" @close="deptShow = false" @confirm="onConfirmDept" closeOnClickOverlay></u-picker> -->
				</u-form-item>
				<u-form-item label="被访人" label-width="110rpx" prop="bfUserName" required>
					<u-input class="form-input" v-model="form.bfUserName" placeholder="请输入被访人" />
				</u-form-item>
				<u-form-item label="来访人数" label-width="140rpx" prop="lfRs" required>
					<u-input class="form-input" v-model="form.lfRs" placeholder="请输入来访人数" />
				</u-form-item>
				<u-form-item label="来访事由" label-width="140rpx" prop="lfSy" required>
					<u-textarea v-model="form.lfSy" placeholder="请输入来访事由" count autoHeight maxlength="60" disableDefaultPadding />
				</u-form-item>
				<u-form-item label="访客车牌" label-width="140rpx" prop="fkCl">
					<!-- <u-input class="form-input" v-model="form.fkCl" placeholder="请输入访客车牌" /> -->
					<car-number-input @numberInputResult="numberInputResult" :defaultStr="form.fkCl"></car-number-input>
				</u-form-item>
				<u-form-item label="访客人脸" label-width="140rpx" prop="fkRl">
					<u-upload :fileList="form.fkRl" @afterRead="afterRead" @delete="deletePic" name="fkRl" multiple
						:maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item label="相关图片" label-width="140rpx" prop="xgTp">
					<u-upload :fileList="form.xgTp" @afterRead="afterRead" @delete="deletePic" name="xgTp" multiple
						:maxCount="9"></u-upload>
				</u-form-item>
				<u-form-item label="其他补充" label-width="140rpx" prop="qtBc">
					<u-textarea class="form-input" v-model="form.qtBc" count autoHeight maxlength="60" placeholder="请输入其他补充" disableDefaultPadding />
				</u-form-item>
			</view>
		</u-form>
		<view class="u-margin-top-30" @click="submitAction">
			<animate-button ref="animeBtn" btn-text="提交"></animate-button>
		</view>
		<u-toast ref="uToast"></u-toast>
		<u-gap height="30"></u-gap>
		<custom-footer :current="current" />
		<well-treeSelect
			@doConfirm="doConfirmCategorys"
			:showDialog.sync="deptShow"
			:data="deptList"
			:title-text="'选择要拜访的公司部门'"
			:max-selected="1"
			:selectedValues="selectedDeptValues"
			v-if="deptList.length != 0">
		</well-treeSelect>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				current: 1,
				form: {
					lfTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'), // 申请时间段
					visitTimeEnd: uni.$u.timeFormat(new Date(new Date().getTime() + 3 * 60 * 60 * 1000), 'yyyy-mm-dd hh:MM'), // 申请时间段
					userName: '', // 申请人
					userPhone: '', // 申请人电话
					bfDept: 0, // 拜访部门
					bfDeptName: '', // 拜访部门
					bfUserName: '', // 被访人
					lfRs: 1, // 来访人数
					lfSy: '', // 来访事由
					fkCl: '', // 访客车牌
					fkRl: [], // 访客人脸
					qtBc: '', // 其他补充
					xgTp: [], // 相关图片
				},
				rules: {
					lfTime: {
						type: 'string',
						required: true,
						message: '请选择申请来访开始日期',
						trigger: ['blur', 'change']
					},
					visitTimeEnd: {
						type: 'string',
						required: true,
						message: '请选择申请来访结束日期',
						trigger: ['blur', 'change']
					},
					userName: {
						type: 'string',
						required: true,
						message: '请输入申请人',
						trigger: ['blur', 'change']
					},
					userPhone: {
						type: 'string',
						required: true,
						message: '请输入申请人电话',
						trigger: ['blur', 'change']
					},
					bfDeptName: {
						type: 'string',
						required: true,
						message: '请选择拜访部门',
						trigger: ['blur', 'change']
					},
					bfUserName: {
						type: 'string',
						required: true,
						message: '请输入拜访人',
						trigger: ['blur', 'change']
					},
					// fkCl: {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入访客车牌',
					// 	trigger: ['blur', 'change']
					// },
					// fkRl: {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入访客人脸',
					// 	trigger: ['blur', 'change']
					// },
					lfRs: {
						type: 'number',
						required: true,
						message: '请输入来访人数',
						trigger: ['blur', 'change']
					},
					lfSy: {
						type: 'string',
						required: true,
						message: '请输入来访事由',
						trigger: ['blur', 'change']
					},
					// qtBc: {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入其他补充',
					// 	trigger: ['blur', 'change']
					// },
					// xgTp: {
					// 	type: 'array',
					// 	required: true,
					// 	message: '请上传相关图片',
					// 	trigger: ['blur', 'change']
					// },
				},

				dateShow: false,
				dateShow1: false,
				deptShow: false,
				deptList: [
					// [
					// 	{
					// 		id: 1,
					// 		value: '生产部'
					// 	},
					// 	{
					// 		id: 2,
					// 		value: '技术部'
					// 	},
					// 	{
					// 		id: 3,
					// 		value: '行政部'
					// 	}
					// ]
				],
				selectedDeptValues: [],
				
				defaultNum: ''
			};
		},
		computed: {
			getUserInfo() {
				if (Object.keys(this.$store.state.userInfo).length != 0) {
					return this.$store.state.userInfo
				} else if (Object.keys(uni.getStorageSync('userInfo')).length != 0) {
					return uni.getStorageSync('userInfo')
				} else {
					return {}
				}
			},
			deptInfo() {
				if (Object.keys(this.$store.state.deptInfo).length != 0) {
					return this.$store.state.deptInfo
				} else if (Object.keys(uni.getStorageSync('deptInfo')).length != 0) {
					return uni.getStorageSync('deptInfo')
				} else {
					return []
				}
			}
		},
		onLoad() {
			// this.deptList = [this.deptInfo]
			this.deptList = this.arrayToTree(this.deptInfo)
		},
		onShow() {
			this.form.userName = this.getUserInfo.wxName || ''
			this.form.userPhone = this.getUserInfo.wxPhone || ''
		},
		methods: {
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			onConfirmType(item) {
				this.form.lfTime = uni.$u.timeFormat(item.value, 'yyyy-mm-dd hh:MM');
				this.dateShow = false;
			},
			onConfirmType1(item) {
				this.form.visitTimeEnd = uni.$u.timeFormat(item.value, 'yyyy-mm-dd hh:MM');
				this.dateShow1 = false;
			},
			onConfirmDept(item) {
				this.form.bfDept = item.value[0].id;
				this.form.bfDeptName = item.value[0].deptName;
				this.deptShow = false;
				this.$refs.uForm.validateField('bfDeptName');
			},
			submitAction() {
				if (this.$refs.animeBtn.status != 1) return
				this.$refs.uForm.validate().then(res => {
					this.$refs.animeBtn.loading()
					let fkRl = [], xgTp = [];
					for (let i in this.form.fkRl) {
						fkRl.push(this.form.fkRl[i].url)
					}
					for (let i in this.form.xgTp) {
						xgTp.push(this.form.xgTp[i].url)
					}
					this.$api.addVisit({
						...this.form,
						lfTime: this.form.lfTime + ':00',
						visitTimeEnd: this.form.visitTimeEnd + ':00',
						fkRl: fkRl.join(','),
						xgTp: xgTp.join(',')
					}).then(res => {
						wx.requestSubscribeMessage({
							tmplIds: ['GMBhcUrrKYjMQre85K9yRFUBxAA-L5BzuRCZ_B670r8'],
							success (res) {
								console.log(res)
							}
						})
						this.$refs.animeBtn.success()
						this.$refs.uToast.show({
							message: '提交成功',
							type: 'success',
							duration: 1500,
						});
						setTimeout(() => {
							this.$refs.animeBtn.reset()
							this.form = {
								lfTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'), // 申请时间段
								visitTimeEnd: uni.$u.timeFormat(new Date(new Date().getTime() + 3 * 60 * 60 * 1000), 'yyyy-mm-dd hh:MM'), // 申请时间段
								userName: '', // 申请人
								userPhone: '', // 申请人电话
								bfDept: 0, // 拜访部门
								bfDeptName: '', // 拜访部门
								bfUserName: '', // 被访人
								lfRs: 1, // 来访人数
								lfSy: '', // 来访事由
								fkCl: '', // 访客车牌
								fkRl: [], // 访客人脸
								qtBc: '', // 其他补充
								xgTp: [], // 相关图片
							}
							this.$refs.uForm.resetFields()
						}, 1500)
					}).catch(() => {
						this.$refs.animeBtn.fail()
						setTimeout(() => {
							this.$refs.animeBtn.reset()
						}, 3000)
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},

			// 删除图片
			deletePic(event) {
				this.form[event.name].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.form[event.name].length
				lists.map((item) => {
					this.form[event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.form[event.name][fileListLen]
					this.form[event.name].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.$refs.uForm.validateField(event.name);
			},
			uploadFilePromise(path) {
				return new Promise((resolve, reject) => {
					this.$upload.PhotoOrVideo((url, index, type) => {
						uni.showToast({
							title: '上传成功！'
						});
						resolve(url);
					}, {
						path
					})
				})
			},
			
			numberInputResult(e) {
				this.form['fkCl'] = e;
				this.$refs.uForm.validateField('fkCl');
			},
			
			openDeptShow() {
				this.deptShow = true;
			},
			
			doConfirmCategorys(selectedItems) {
				this.form.bfDept = selectedItems[0].value;
				this.form.bfDeptName = selectedItems[0].label;
				this.$refs.uForm.validateField('bfDeptName');
			},
			
			arrayToTree(items) {
			  const result = [];   // 存放结果集
			  const itemMap = {};  // 
			  for (const item of items) {
			    const id = item.id;
			    const pid = item.parentId;
			
			    if (!itemMap[id]) {
			      itemMap[id] = {
			        children: [],
			      }
			    }
			
			    itemMap[id] = {
			      ...item,
			      children: itemMap[id]['children'],
				  label: item.deptName,
				  value: item.id,
			    }
			
			    const treeItem =  itemMap[id];
			
			    if (pid === 0) {
			      result.push(treeItem);
			    } else {
			      if (!itemMap[pid]) {
			        itemMap[pid] = {
			          children: [],
			        }
			      }
			      itemMap[pid].children.push(treeItem)
			    }
			
			  }
			  return result;
			}
			
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.$refs.datetimePicker.setFormatter(this.formatter)
		}
	}
</script>

<style lang="scss" scoped>
	.select-box {
		width: 100%;
	}
</style>